import React, { Component } from "react";

export default class App extends Component {
  state = {
    list: [
      {
        id: `${Math.random()}`.slice(2, 8),
        text: "wocao",
      },
    ],
  };
  myRef = React.createRef();

  render() {
    return (
      <div>
        <input type="text" ref={this.myRef} />
        <button onClick={this.handleClick}>add2</button>

        <ul>
          {this.state.list.map((item, index) => (
            <li key={item.id}>
              {/* 
                dangerouslySetInnerHTML用来将字符串格式的html语句解析成真的html语句渲染到页面上
                这个属性请谨慎使用，因为会有安全风险 
                比如这里，输入框中如果输入的是html语句，那么就会被解析到下面的span标签里，你无法保证未来用户会往里面输入什么内容
                用法也很固定，传一个对象，__html属性对应着你想要解析的文本内容
              */}
              <span dangerouslySetInnerHTML={{ __html: item.text }}></span>
              <button onClick={this.deleteItem(index)}>delete it</button>
              
            </li>
          ))}
        </ul>
        {this.state.list.length == 0 ? <div>暂无代办事项</div> : null}
      </div>
    );
  }

  handleClick = () => {
    this.setState({
      list: [
        ...this.state.list,
        { id: `${Math.random()}`.slice(2, 8), text: this.myRef.current.value },
      ],
    });
    this.myRef.current.value = "";
  };

  deleteItem(index) {
    return () => {
      this.setState({
        list: this.state.list.filter((_, i) => i != index),
      });
    };
  }
}
